package team.seekers.hula.user.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import team.seekers.hula.common.annotation.ApiResponseBody;
import team.seekers.hula.common.entity.UserSessionDTO;
import team.seekers.hula.common.entity.result.ApiException;
import team.seekers.hula.common.entity.result.ApiExceptionEnum;
import team.seekers.hula.common.utils.AssertUtils;
import team.seekers.hula.common.utils.JwtUtil;
import team.seekers.hula.auth.service.MindUtils;
import team.seekers.hula.system.phoneMessage.service.PhoneMessageService;
import team.seekers.hula.user.user.entity.dao.UserDO;
import team.seekers.hula.user.user.entity.dto.UserCreateDTO;
import team.seekers.hula.user.user.entity.dto.UserHulaDTO;
import team.seekers.hula.user.user.entity.dto.UserUpdateDTO;
import team.seekers.hula.user.user.entity.vo.UserInfoVO;
import team.seekers.hula.user.user.service.UserService;
import team.seekers.hula.user.userFollow.entity.vo.UserFocusListVO;
import team.seekers.hula.user.userFollow.entity.vo.UserFollowInfoVO;
import team.seekers.hula.user.userFollow.service.UserFollowerService;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

import static team.seekers.hula.common.entity.result.ApiExceptionEnum.USER_ACCOUNT_ALREADY_EXIST;

/**
 * @author hbc
 * @since 2021-02-15
 */
@Controller
@ApiResponseBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserFollowerService userFollowerService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PhoneMessageService phoneMessageService;

    @GetMapping("/info")
    public UserInfoVO get() {
        return userService.getInfoVO(MindUtils.getUserId());
    }

    @GetMapping("/logout")
    public void logout(HttpServletResponse response) {
        response.setHeader(UserSessionDTO.HEADER_KEY, UserSessionDTO.HEADER_VALUE_LOGOUT);
    }

    @GetMapping("/info/follow")
    public UserFollowInfoVO get(@RequestParam String id) {
        return userService.getFollowInfoVO(id, MindUtils.getUserId());
    }

    @PostMapping("/register")
    public String register(@RequestBody UserCreateDTO userCreateDTO) {
        //校验用户名
        QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
        wrapper.eq("tel", userCreateDTO.getTel())
                .or().eq("union_id", userCreateDTO.getUnionId())
                .or().eq("account", userCreateDTO.getAccount());
        int count = userService.count(wrapper);
        if (count != 0) {
            throw new ApiException(USER_ACCOUNT_ALREADY_EXIST);
        }
        return jwtUtil.getAndCacheJwtToken(userService.add(userCreateDTO));
    }

    @PostMapping("/hula")
    public String hula(@RequestBody UserHulaDTO userHulaDTO) {
        userHulaDTO.setId(MindUtils.getUserId());
        return jwtUtil.getAndCacheJwtToken(userService.toBeHula(userHulaDTO));
    }

    @PostMapping("/update")
    public void update(@RequestBody UserUpdateDTO userUpdateDTO) {
        userUpdateDTO.setId(MindUtils.getUserId());
        if (StringUtils.isNotBlank(userUpdateDTO.getAccount())) {
            //校验用户名
            QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
            wrapper.eq("account", userUpdateDTO.getAccount());
            int count = userService.count(wrapper);
            if (count != 0) {
                throw new ApiException(USER_ACCOUNT_ALREADY_EXIST);
            }
        }
        userService.update(userUpdateDTO);
    }


    // 微信号绑定手机号已注册账号
    @PostMapping("/bindWxAndPhone")
    @ApiResponseBody
    public String bindWxAndPhone(@RequestBody Map<String, String> json,
                                 @RequestHeader("user-agent") String userAgent) {
        String phone = json.get("phone");
        String unionId = json.get("unionId");
        if (!StringUtils.isNotBlank(phone)) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入手机号");
        }
        if (!StringUtils.isNotBlank(unionId)) {
            throw AssertUtils.newException(ApiExceptionEnum.SYSTEM_FAIL, "系统异常，unionId缺失");
        }
        if (!StringUtils.isNotBlank(json.get("code"))) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入验证码");
        }
        phoneMessageService.verifyCaptcha(phone, json.get("code"));
        userService.bindWxAndPhone(phone, unionId);
        return jwtUtil.getAndCacheJwtToken(userService.getUserSessionByTel(phone));
    }


    // 绑定或修改账号
    @PostMapping("/bindAccount")
    @ApiResponseBody
    public String bindAccount(@RequestBody Map<String, String> json) {
        String phone = json.get("phone");
        String account = json.get("account");
        if (!StringUtils.isNotBlank(phone)) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入手机号");
        }
        if (!StringUtils.isNotBlank(account)) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入账号");
        }
        if (!StringUtils.isNotBlank(json.get("code"))) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入验证码");
        }
        phoneMessageService.verifyCaptcha(phone, json.get("code"));
        userService.bindAccount(phone, account);
        return jwtUtil.getAndCacheJwtToken(userService.getUserSessionByTel(phone));
    }

    // 绑定或修改密码
    @PostMapping("/bindPassword")
    @ApiResponseBody
    public String bindPassword(@RequestBody Map<String, String> json) {
        String phone = json.get("phone");
        String password = json.get("password");
        if (!StringUtils.isNotBlank(phone)) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入手机号");
        }
        if (!StringUtils.isNotBlank(password)) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入密码");
        }
        if (!StringUtils.isNotBlank(json.get("code"))) {
            throw AssertUtils.newException(ApiExceptionEnum.PARAM_NOT_VALID, "请输入验证码");
        }
        phoneMessageService.verifyCaptcha(phone, json.get("code"));
        userService.bindPassword(phone, password);
        return jwtUtil.getAndCacheJwtToken(userService.getUserSessionByTel(phone));
    }


    @GetMapping("/follow/change")
    public void follow(@RequestParam String id) {
        userService.followOrUnFollowUser(MindUtils.getUserId(), id);
    }

    //获取当前用户的关注列表
    @GetMapping("/listFocusByActivity")
    public List<UserFocusListVO> listAllFocus() {
        return userFollowerService.listAllFocus();
    }

}

